package com.jinzhi.jzweb.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.utils.Result;
import com.jinzhi.jzweb.domain.CoursesDO;
import com.jinzhi.jzweb.domain.TrainingAnswerSheetDO;
import com.jinzhi.jzweb.domain.TrainingPapersDO;
import com.jinzhi.jzweb.domain.TrainingQuestionsDO;
import com.jinzhi.jzweb.service.CoursesService;
import com.jinzhi.jzweb.service.TrainingAnswerSheetService;
import com.jinzhi.jzweb.service.TrainingPapersService;
import com.jinzhi.jzweb.service.TrainingQuestionsService;
import com.jinzhi.sys.domain.UserDO;
import com.jinzhi.sys.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 
 * <pre>
 * 培训答卷表
 * </pre>
 * <small> 2020-02-24 21:00:11 | lance</small>
 */
@Controller
@RequestMapping("/jzweb/trainingAnswerSheet")
public class TrainingAnswerSheetController extends BaseController {
	@Autowired
	private TrainingAnswerSheetService trainingAnswerSheetService;
	@Autowired
	private TrainingPapersService trainingPapersService;
	@Autowired
	private UserService userService;
	@Autowired
	private CoursesService coursesService;
	@Autowired
	private TrainingQuestionsService trainingQuestionsService;
	
	@GetMapping()
	@RequiresPermissions("jzweb:trainingAnswerSheet:trainingAnswerSheet")
	String TrainingAnswerSheet(){
	    return "jzweb/trainingAnswerSheet/trainingAnswerSheet";
	}
	
	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("jzweb:trainingAnswerSheet:trainingAnswerSheet")
	public Result<Page<TrainingAnswerSheetDO>> list(HttpServletRequest req, TrainingAnswerSheetDO trainingAnswerSheetDTO){
		Wrapper<TrainingAnswerSheetDO> wrapper = new EntityWrapper<TrainingAnswerSheetDO>().orderBy("id", false);
		if (trainingAnswerSheetDTO.getState() != null){
			wrapper.eq("state",trainingAnswerSheetDTO.getState());
		}
		if (StringUtils.isNotBlank(trainingAnswerSheetDTO.getTpapersName())){
			Wrapper<TrainingPapersDO> Wrapper = new EntityWrapper<TrainingPapersDO>().like("name",trainingAnswerSheetDTO.getTpapersName());
			String roleNames = getRoleNames();
			String straa = "";
			if (!roleNames.contains("超级用户角色")) {
				Long orgids;
				Object orgId = req.getSession().getAttribute("orgId");
				if (orgId != null) {
					orgids = Long.parseLong(orgId.toString());
				} else {
					orgids = this.getUser().getOrgId();
				}
				List<CoursesDO> coursesDOS;
				if(roleNames.contains("讲师")){
					coursesDOS = coursesService.findByKv("org_id", orgids,"userId",this.getUserId());//讲师
				}else{
					coursesDOS = coursesService.findByKv("org_id", orgids);//其他角色，比如培训机构
				}
				for (CoursesDO coursesDO : coursesDOS) {
					straa = straa + coursesDO.getId() + ",";
				}
				Wrapper.and();
				if(StringUtils.isNotBlank(straa)){
					Wrapper.in("courses_id",straa.substring(0,straa.length()-1));
				}else{
					Wrapper.eq("courses_id",null);
				}
			}
			List<TrainingPapersDO>  trainingPapersDOS = trainingPapersService.selectList(Wrapper);
			String str = "";
			for (TrainingPapersDO trainingPapersDO : trainingPapersDOS){
				str = str + trainingPapersDO.getId() + ",";
			}
			wrapper.and();
			if(StringUtils.isNotBlank(str)){
				wrapper.in("tpapers_id",str.substring(0,str.length()-1));
			}else{
				wrapper.eq("tpapers_id",null);
			}
		}else{
			String roleNames = getRoleNames();
			String straa = "";
			if (!roleNames.contains("超级用户角色")) {
				Long orgids;
				Object orgId = req.getSession().getAttribute("orgId");
				if (orgId != null) {
					orgids = Long.parseLong(orgId.toString());
				} else {
					orgids = this.getUser().getOrgId();
				}
				List<CoursesDO> coursesDOS;
				if(roleNames.contains("讲师")){
					coursesDOS = coursesService.findByKv("org_id", orgids,"user_id",this.getUserId());//讲师
				}else{
					coursesDOS = coursesService.findByKv("org_id", orgids);//其他角色，比如培训机构
				}

				for (CoursesDO coursesDO : coursesDOS) {
					straa = straa + coursesDO.getId() + ",";
				}
				List<TrainingPapersDO> trainingPapersDOS;
				if(StringUtils.isNotBlank(straa)){
					Wrapper<TrainingPapersDO> wrapperss = new EntityWrapper<TrainingPapersDO>();
					wrapperss.in("courses_id",straa.substring(0,straa.length()-1));
					trainingPapersDOS = trainingPapersService.selectList(wrapperss);
				}else{
					trainingPapersDOS = new ArrayList<>();
				}
				String str = "";
				for (TrainingPapersDO trainingPapersDO : trainingPapersDOS){
					str = str + trainingPapersDO.getId() + ",";
				}
				wrapper.and();
				if(StringUtils.isNotBlank(str)){
					wrapper.in("tpapers_id",str.substring(0,str.length()-1));
				}else{
					wrapper.eq("tpapers_id",null);
				}
			}

		}
		if (StringUtils.isNotBlank(trainingAnswerSheetDTO.getUserName())){
			Wrapper<UserDO> Wrapper = new EntityWrapper<UserDO>().like("name",trainingAnswerSheetDTO.getUserName());
			List<UserDO>  userDOS = userService.selectList(Wrapper);
			String str = "";
			for (UserDO userDO : userDOS){
				str = str + userDO.getId() + ",";
			}
			wrapper.and();
			if(StringUtils.isNotBlank(str)){
				wrapper.in("user_id",str.substring(0,str.length()-1));
			}else{
				wrapper.eq("user_id",null);
			}
		}

        Page<TrainingAnswerSheetDO> page = trainingAnswerSheetService.selectPage(getPage(TrainingAnswerSheetDO.class), wrapper);
		List list = new ArrayList();
		for (int i = 0; i < page.getRecords().size(); i++) {
			TrainingAnswerSheetDO obj = (TrainingAnswerSheetDO) page.getRecords().get(i);
			if (obj.getUserId() != null){
				UserDO userDO = userService.selectById(obj.getUserId());
				if (userDO != null) {
					if(StringUtils.isNotBlank(userDO.getName())){
						obj.setUserName(userDO.getName());
					}else{
						obj.setUserName(userDO.getUsername());
					}
				}
			}
			if (obj.getTpapersId() != null){
				TrainingPapersDO trainingPapersDO = trainingPapersService.selectById(obj.getTpapersId());
				if (trainingPapersDO != null) {
					obj.setTpapersName(trainingPapersDO.getName());
				}
			}
			list.add(obj);
		}
		page.setRecords(list);
        return Result.ok(page);
	}
	
	@GetMapping("/add")
	@RequiresPermissions("jzweb:trainingAnswerSheet:add")
	String add(){
	    return "jzweb/trainingAnswerSheet/add";
	}

	@GetMapping("/edit/{id}")
	@RequiresPermissions("jzweb:trainingAnswerSheet:edit")
	String edit(@PathVariable("id") Long id,Model model){
		TrainingAnswerSheetDO trainingAnswerSheet = trainingAnswerSheetService.selectById(id);
		model.addAttribute("trainingAnswerSheet", trainingAnswerSheet);
	    return "jzweb/trainingAnswerSheet/edit";
	}

	@GetMapping("/info/{id}")
	@RequiresPermissions("jzweb:trainingAnswerSheet:trainingAnswerSheet")
	String info(@PathVariable("id") Long id, Model model) {
		TrainingAnswerSheetDO trainingAnswerSheet = trainingAnswerSheetService.selectById(id);
		if (trainingAnswerSheet.getTpapersId() != null) {
			TrainingPapersDO trainingPapersDO = trainingPapersService.selectById(trainingAnswerSheet.getTpapersId());
			if (trainingPapersDO != null) {
				trainingAnswerSheet.setTpapersName(trainingPapersDO.getName());
			}
		}
		if (trainingAnswerSheet.getUserId() != null) {
			UserDO userDO = userService.selectById(trainingAnswerSheet.getUserId());
			if (userDO != null) {
				if(StringUtils.isNotBlank(userDO.getName())){
					trainingAnswerSheet.setUserName(userDO.getName());
				}else{
					trainingAnswerSheet.setUserName(userDO.getUsername());
				}
			}
		}
		List<Map> maps = new ArrayList<>();
		Integer results = 0;
		String[] ssr = trainingAnswerSheet.getAnswers().split("\\{\"id\":\"");
		for (int i = 1; i < ssr.length; i++) {
			Map map = new HashMap();
			String[] ssc = ssr[i].split("\"}");
			for (int j = 0; j < ssc.length; j++) {
				String[] ssa = ssc[j].split("\",\"value\":\"");
				if (ssa.length > 1) {
					TrainingQuestionsDO trainingQuestionsDO = trainingQuestionsService.selectById(ssa[0]);
					map.put("titleNumber",i);//题号
					map.put("introduce",trainingQuestionsDO.getIntroduce());//题目内容
					map.put("titleOptions",trainingQuestionsDO.getOptions());//题目选项
					if (trainingQuestionsDO.getType() == 0 || trainingQuestionsDO.getType() == 2) {//单选题和判断题，答案唯一，可以不用拆解了
						if (trainingQuestionsDO.getRightKey().equals(ssa[1])) {
							map.put("answers",trainingQuestionsDO.getRightKey());//正确答案
							map.put("options",ssa[1]);//考生选项
							map.put("yesOrNo","是");
							results = results + trainingQuestionsDO.getScore();
						}else{
							map.put("answers",trainingQuestionsDO.getRightKey());//正确答案
							map.put("options",ssa[1]);//考生选项
							map.put("yesOrNo","否");
						}
					} else if (trainingQuestionsDO.getType() == 1) {//多选题因为答案有多个，需要循环判断一下是否包含该答案
						String[] ssb = ssa[1].split(";;");
						String answer = "";
						for (int n = 0; n < ssb.length; n++) {
							if(answer == ""){
								answer = ssb[n];
							}else{
								answer = answer + ";;" +ssb[n];
							}
						}

						if(trainingQuestionsDO.getRightKey().equals(answer)){
							map.put("answers",trainingQuestionsDO.getRightKey());//正确答案
							map.put("options",answer);//考生选项
							map.put("yesOrNo","是");
							results = results + trainingQuestionsDO.getScore();
						}else{
							map.put("answers",trainingQuestionsDO.getRightKey());//正确答案
							map.put("options",answer);//考生选项
							map.put("yesOrNo","否");
						}
					}
					maps.add(map);
				}else if(ssa.length == 1 && !ssa[0].equals(",") && !ssa[0].equals("]")){
					TrainingQuestionsDO trainingQuestionsDO = trainingQuestionsService.selectById(ssa[0]);
					map.put("titleNumber",trainingQuestionsDO.getTitleNumber());//题号
					map.put("introduce",trainingQuestionsDO.getIntroduce());//题目内容
					map.put("titleOptions",trainingQuestionsDO.getOptions());//题目选项
					map.put("answers",trainingQuestionsDO.getRightKey());//正确答案
					map.put("options","");//考生选项
					map.put("yesOrNo","否");

					maps.add(map);
				}
			}
		}
		trainingAnswerSheet.setAnswerLists(maps);
		trainingAnswerSheet.setScore(results);
		model.addAttribute("trainingAnswerSheet", trainingAnswerSheet);
		return "jzweb/trainingAnswerSheet/info";
	}
	
	@Log("添加培训答卷表")
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("jzweb:trainingAnswerSheet:add")
	public Result<String> save( TrainingAnswerSheetDO trainingAnswerSheet){
		trainingAnswerSheetService.insert(trainingAnswerSheet);
        return Result.ok();
	}
	
	@Log("修改培训答卷表")
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("jzweb:trainingAnswerSheet:edit")
	public Result<String>  update( TrainingAnswerSheetDO trainingAnswerSheet){
		boolean update = trainingAnswerSheetService.updateById(trainingAnswerSheet);
		return update ? Result.ok() : Result.fail();
	}
	
	@Log("删除培训答卷表")
	@PostMapping( "/remove")
	@ResponseBody
	@RequiresPermissions("jzweb:trainingAnswerSheet:remove")
	public Result<String>  remove( Long id){
		trainingAnswerSheetService.deleteById(id);
        return Result.ok();
	}
	
	@Log("批量删除培训答卷表")
	@PostMapping( "/batchRemove")
	@ResponseBody
	@RequiresPermissions("jzweb:trainingAnswerSheet:batchRemove")
	public Result<String>  remove(@RequestParam("ids[]") Long[] ids){
		trainingAnswerSheetService.deleteBatchIds(Arrays.asList(ids));
		return Result.ok();
	}
	
}
